package com.baidu.mpks.common;

import com.baidu.mpks.exception.BusinessException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

@Aspect
@Component
@Order(1)
public class UserAuthorizedAspect extends BaseAuthorizedAspect {

    private static final Logger log = LoggerFactory.getLogger(UserAuthorizedAspect.class);

    public UserAuthorizedAspect() {
    }

    @Around("execution(public * com.baidu.mpks.util.SecurityUtil.getUserIdOrDefault(String))")
    public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Map<String, String> headers = this.fillHeaders();
        if (null != headers.get("token") && null != headers.get("userid")) {
            args[0] = headers.get("userid");
        }

        return joinPoint.proceed(args);
    }

    @Before("execution(public * com.baidu.mpks..*.web.*.*(..)) && @annotation(authorized)")
    public void runBefore(JoinPoint joinPoint, Authorized authorized) {
        try {
            if (authorized != null && authorized.value().length > 0) {
                Map<String, String> headers = this.fillHeaders();
                if (null != headers.get("token")) {
                    return;
                }

                log.debug("headers -------> {}", (new ObjectMapper()).writeValueAsString(headers));
                String authHeader = (String)headers.get("authorities");
                if (null != authHeader && this.isMatchedAuthority(Lists.newArrayList(authHeader.split(",")), authorized.value())) {
                    return;
                }

                throw new BusinessException("当前用户没有" + (new ObjectMapper()).writeValueAsString(authorized.value()) + "权限");
            }
        } catch (JsonProcessingException var5) {
            log.error("" + var5);
        }

    }
}
